﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using System.Collections.Generic;
using System.IO;
using Tauren.Form.Entity.Config;

namespace Tauren.Form.Core.ConfigExtension
{
    /// <summary>
    /// auto 引用
    /// </summary>
    public class AutoFacModule : Module
    {

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<RequestInterceptor>();
            builder.RegisterAssemblyTypes(System.Reflection.Assembly.Load("Tauren.Form.Service")).AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired().InstancePerDependency().EnableInterfaceInterceptors().InterceptedBy(typeof(RequestInterceptor));
            foreach (var item in GetAssmenBlys())
            {
                builder.RegisterAssemblyTypes(item).AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired().InstancePerDependency();
            }
        }

        /// <summary>
        /// 返回需要依赖注入的接口
        /// </summary>
        /// <returns></returns>
        private System.Reflection.Assembly[] GetAssmenBlys()
        {
            IConfigFile con = new GeneralConfFileOperator();
            Assemblys assembly = new Assemblys();
            string path = Directory.GetCurrentDirectory() + "\\Config\\Assemblys.xml";
            assembly = con.ReadConfFile<Assemblys>(path, false);
            List<System.Reflection.Assembly> assemblys = new List<System.Reflection.Assembly>();
            if (assembly.childs.Count > 0)
            {
                foreach (var item in assembly.childs)
                {
                    assemblys.Add(System.Reflection.Assembly.Load(item));
                }

            }
            return assemblys.ToArray();
        }
    }
}
